import java.io.*;
import java.net.Socket;

public class TCPCopyPictureClient {
    public static void main(String[] args) {
        try {
            Socket client = new Socket("127.0.0.1", 8888);

            // 获取字节输入流
            InputStream inputStream = client.getInputStream();
            // 将字节流转为字符流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            // 将字符流转为缓冲字符流
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String fileName = bufferedReader.readLine();
            System.out.println("文件名：" + fileName);

            String line = bufferedReader.readLine();
            long size = Long.parseLong(line);
            System.out.println("大小：" + line);

            FileOutputStream fileOutputStream = new FileOutputStream("copy " + fileName);

            byte[] bytes = new byte[8192];
            int length = 0;
            int receiveLength = 0;
            while (((length = inputStream.read(bytes)) != -1)) {
                fileOutputStream.write(bytes, 0, length);
                System.out.println(length);
                receiveLength += length;
                if (receiveLength == size){
                    break;
                }
            }

            fileOutputStream.close();

            String info = "客户端接收完毕";
            OutputStream outputStream = client.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(info);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStreamWriter.close();
            outputStream.close();

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            client.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
